using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using IQIGame.Rendering;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering.Universal;

namespace IQIGame.Onigao.Game
{
    public static class RenderBlurUtil
    {
        static Dictionary<string, RenderTexture> tempBlurRTMap = new Dictionary<string, RenderTexture>();

        static RenderTexture GetTemplateBlurRT(string name, int downSampling = 1)
        {
            if (tempBlurRTMap.TryGetValue(name, out var rt))
                return rt;

            downSampling = Mathf.Max(1, downSampling);
            int w = (int)(Screen.width / downSampling);
            int h = (int)(Screen.height / downSampling);
            rt = GameRender.Instance.GetTemporaryRT(w, h, name);
            tempBlurRTMap[name] = rt;
            return rt;
        }

        //添加RT引用名，方便查找内存泄露问题
        //异步获取模糊背景，依赖后效框架设计，等待2帧后获取模糊结果
        public static async UniTask<RenderTexture> GetBlurTexAsyncReadBack(string name, GameRender.CameraType cameraType, int downSampling = 2)
        {
            var blurVolume = GameRenderPostProcess.Instance.GetVoume(cameraType, RenderPassEvent.BeforeRenderingPostProcessing, typeof(BlurVolume));
            if (blurVolume == null)
            {
                LogGame.LogWarning("Cant't find UICamera Blur Component");
                return null;
            }

            var rt = GetTemplateBlurRT(name, downSampling);
            //后效框架不提供直接渲染接口，只提供插入渲染命令
            //设置模糊渲染目标
            blurVolume.PaintOneFrame(rt);
            await UniTask.Yield();
            await UniTask.Yield();
            return rt;
        }

        public static void ReleaseBlurRT(string name)
        {
            if (tempBlurRTMap.TryGetValue(name, out var rt))
                GameRender.Instance.ReleaseTemporaryRT(rt);

            tempBlurRTMap.Remove(name);
        }

        public static void ReleaseAllBlurRT()
        {
            foreach (var rt in tempBlurRTMap)
                GameRender.Instance.ReleaseTemporaryRT(rt.Value);
            tempBlurRTMap.Clear();
        }
    }
}
